package com.dongway.core.web;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.dongway.core.common.BaseRuntimeException;
import com.dongway.core.common.Paginator;
import com.dongway.core.common.ProcResult;
import com.dongway.core.common.WebServiceResult;
import com.dongway.core.web.converter.DatePropertyEdit;
import com.dongway.core.web.converter.TimePropertyEdit;

public abstract class AbstractBaseController {

    // 访问根路径
    private static final String PATH_ROOT = "/";
    // 日记
    protected Logger logger = LoggerFactory.getLogger(getClass());


    // @Autowired
    // protected ResourceContextHolder resourceContextHolder;
    //
    // /**
    // * 上传文件根目录
    // * @return
    // */
    // protected String getUploadPath() {
    // return normalizePath(resourceContextHolder.getUploadPath());
    // }
    //
    // /**
    // * 下载文件路径
    // * @return
    // */
    // protected String getDownloadUrl() {
    // return resourceContextHolder.getDownloadUrl();
    // }

    /**
     * 跳转到指定页 ,浏览器显示跳转后的地址
     * 
     * @param path
     * @return
     */
    protected String redirect(String path) {
        String url = converUrl(path);
        if (logger.isDebugEnabled()) {
            logger.debug("redirect url is " + url);
        }
        return "redirect:" + url;
    }


    /**
     * 返回模块视图(JSP文件)根目录路径,默认返回""
     * 
     * @return
     */
    protected String getModelViewPath() {
        return StringUtils.EMPTY;
    }


    /**
     * 返回模块访问路径,默认返回"/"
     * 
     * @return
     */
    protected String getModelPath() {
        return PATH_ROOT;
    }


    /**
     * 将模块相对路径转化为项目相对路径
     * 
     * @param path
     * @return
     */
    protected String converUrl(final String path) {
        String _path = StringUtils.trimToEmpty(path);
        StringBuffer buf = new StringBuffer();
        // 获取默认模块返回路径
        String modelPath = StringUtils.trimToEmpty(getModelPath());
        if (!_path.startsWith(modelPath)) {
            buf.append(modelPath);
            if (!modelPath.endsWith("/")) {
                buf.append("/");
            }
        }
        buf.append(_path);
        return normalizePath(buf.toString());
    }


    /**
     * 将模块相对路径视图(JSP)转化为项目相对路径视图
     * 
     * @param path
     * @return
     */
    protected String converPath(final String path) {
        String _path = StringUtils.trimToEmpty(path);
        StringBuffer buf = new StringBuffer();
        // 获取默认模块返回路径
        String viewPath = StringUtils.trimToEmpty(getModelViewPath());
        if (!_path.startsWith(viewPath)) {
            buf.append(viewPath);
            if (!viewPath.endsWith("/")) {
                buf.append("/");
            }
        }
        buf.append(_path);
        return normalizePath(buf.toString());
    }


    // /**
    // * 将图片相对址转化为绝对地址
    // * @param path
    // * @return
    // */
    // protected String converImagePath(final String path) {
    // if (StringUtils.isBlank(path)) {
    // return null;
    // } else {
    // StringBuffer buf = new StringBuffer(getDownloadUrl());
    // if (buf.length() == 0 || buf.charAt(buf.length() - 1) != '/') {
    // buf.append("/");
    // }
    // String _path = normalizePath(path);
    // if (_path.startsWith("/")) {
    // buf.append(_path.substring(1));
    // } else {
    // buf.append(_path);
    // }
    // return buf.toString();
    // }
    // }

    /**
     * 替换 \\ // .. 为 /
     * 
     * @param path
     * @return
     */
    protected String normalizePath(final String path) {
        String _path = StringUtils.trimToEmpty(path);
        _path = _path.replace("\\", "/").replace("\\", "/").replace("//", "/").replace("//", "/");
        return _path;
    }


    /**
     * 前台json数据返回成功
     * 
     * @param data
     * @param paginator
     * @return
     */
    protected Object JsonSuccess(Object data, Paginator paginator) {
        @SuppressWarnings("rawtypes")
        WebServiceResult result = JsonResult(data, null);
        if (paginator != null) {
            result.setTotalRecords(paginator.getTotalRecords());
            result.setLastRecored(paginator.getEndIndex());
        }
        return result;
    }


    /**
     * 前台json数据返回成功
     * 
     * @param data
     * @return
     */
    @SuppressWarnings("rawtypes")
    protected WebServiceResult JsonSuccess(Object data) {
        if (logger.isDebugEnabled()) {
            logger.debug("return data is " + data);
        }
        return JsonResult(data, null);
    }


    /**
     * 前台json数据返回失败
     * 
     * @param e
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    protected WebServiceResult JsonFailed(Exception e) {
        logger.error(e.getMessage(), e);
        WebServiceResult result = new WebServiceResult();
        result.setResult(false);
        result.setMessage(e.getLocalizedMessage());
        if (e instanceof BaseRuntimeException) {
            BaseRuntimeException be = (BaseRuntimeException) e;
            result.setCode(be.getMessageCode());
            result.setData(null != be.getData() ? be.getData() : be.getErrors());
        }
        return result;
    }


    /**
     * 前台json数据返回
     * 
     * @param data
     * @param msg
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    protected WebServiceResult JsonResult(Object data, String msg) {
        WebServiceResult result = new WebServiceResult();
        if (data == null) {
            result.setResult(false);
        }
        result.setMessage(msg);
        result.setData(data);
        if (logger.isDebugEnabled()) {
            logger.debug("return  is " + result);
        }
        return result;
    }


    /**
     * 后台dwz格式的json数据返回成功
     * 
     * @return
     */
    protected ProcResult DWZsuccess() {
        return DWZsuccess(null);
    }


    /**
     * 后台dwz格式的json数据返回 成功
     * 
     * @param obj
     * @return
     */
    protected ProcResult DWZsuccess(Object obj) {
        ProcResult result = new ProcResult();
        result.setCallbackType("refresh");
        result.setMessage("操作成功!");
        result.setData(obj);
        return result;
    }


    /**
     * 后台dwz格式的json数据返回 失败
     * 
     * @param msg
     * @return
     */
    protected ProcResult DWZFailed(String msg) {
        ProcResult result = new ProcResult();
        result.setStatusCode(300);
        result.setMessage(msg);
        return result;
    }


    /**
     * 后台dwz格式的json数据返回 失败
     * 
     * @param e
     * @return
     */
    protected ProcResult DWZFailed(Exception e) {
        ProcResult result = new ProcResult();
        result.setForwardUrl("login.htm");
        result.setMessage(e.getMessage());
        result.setStatusCode(e instanceof RuntimeException ? 300 : 301);
        if (e instanceof BaseRuntimeException) {
            BaseRuntimeException ex = (BaseRuntimeException) e;
            result.setErrorCode(ex.getMessageCode());
            result.setData(null != ex.getData() ? ex.getData() : ex.getErrors());
        }
        return result;
    }


    /**
     * 数据绑定
     * 
     * @param binder
     */
    @InitBinder
    public void binder(WebDataBinder binder) {
        // java.util.Date
        DatePropertyEdit datePropertyEditor = new DatePropertyEdit(java.util.Date.class);
        binder.registerCustomEditor(java.util.Date.class, datePropertyEditor);
        // java.sql.Date
        DatePropertyEdit sDatePropertyEditor = new DatePropertyEdit(java.sql.Date.class);
        binder.registerCustomEditor(java.sql.Date.class, sDatePropertyEditor);
        // java.sql.Time
        binder.registerCustomEditor(java.sql.Time.class, new TimePropertyEdit());
    }
}
